package net.jeanhwea.gold;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jeanhwea.gold.model.DataManager;

/**
 * Servlet implementation class GoldServlet
 */
@WebServlet(description = "A main controller", urlPatterns = { "/" })
public class GoldServlet extends HttpServlet implements Servlet{
	private static final long serialVersionUID = 1L;
			 
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GoldServlet() {
		super();
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		System.out.println("*** initializing controller servlet -> Start");
		super.init(config);
		
		DataManager dataManager = new DataManager();
		dataManager.setDbURL(config.getInitParameter("databaseURL"));
		dataManager.setDbUser(config.getInitParameter("databaseUser"));
		dataManager.setDbPasswd(config.getInitParameter("databasePasswd"));
			
		ServletContext context = config.getServletContext();
		context.setAttribute("base", config.getInitParameter("base"));
		context.setAttribute("dataManager", dataManager);
		
		// load the database JDBC driver
		String driver = config.getInitParameter("jdbcDriver");
		if(driver != null){
			try {  
				Class.forName(driver);
			}
			catch (ClassNotFoundException e) {
				System.out.println(e.toString());
			}
		}
		System.out.println("*** initializing controller servlet -> Done");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		init();
		String base = "/gold/jsp/";
		String url = base + "index.jsp";
		String action = request.getParameter("action");
		if(action != null) {
			switch(action) {
			case "search":
				url = base + "SearchResult.jsp";
				break;
			case "showByID" :
				url = base + "ShowResultByID.jsp";
				break;
			case "showByPrice" :
				url = base + "ShowResultByPrice.jsp";
				break;
			default:
				url = base + "index.jsp";
				break;
			}
		}
		RequestDispatcher reqDispatcher = this.getServletContext().getRequestDispatcher(url);
		reqDispatcher.forward(request, response);
	}

}
